{
 "cells": [
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "# 1、字符串输出解析器 StrOutputParser",
   "id": "81e0db16d8968f18"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-08-27T06:11:47.790325Z",
     "start_time": "2025-08-27T06:11:41.384580Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 1、获取大模型\n",
    "from langchain_core.messages import HumanMessage, SystemMessage\n",
    "from langchain_core.output_parsers import StrOutputParser, XMLOutputParser\n",
    "\n",
    "import os\n",
    "import dotenv\n",
    "from langchain_core.utils import pre_init\n",
    "from langchain_openai import ChatOpenAI\n",
    "\n",
    "dotenv.load_dotenv()\n",
    "\n",
    "os.environ['OPENAI_API_KEY'] = os.getenv(\"OPENAI_API_KEY1\")\n",
    "os.environ['OPENAI_BASE_URL'] = os.getenv(\"OPENAI_BASE_URL\")\n",
    "\n",
    "chat_model = ChatOpenAI(model=\"gpt-4o-mini\")\n",
    "\n",
    "# 2、调用大模型\n",
    "response = chat_model.invoke(\"什么是大语言模型？\")\n",
    "# print(type(response))   #AIMessage\n",
    "\n",
    "#3、如何获取一个字符串的输出结果呢？\n",
    "# 方式1：自己调用输出结果的content\n",
    "# print(response.content)\n",
    "\n",
    "# 方式2：使用StrOutputParser\n",
    "parser = StrOutputParser()\n",
    "str_response = parser.invoke(response)\n",
    "print(type(str_response))  #<class 'str'>\n",
    "print(str_response)\n"
   ],
   "id": "6e089b3a35d986f1",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'str'>\n",
      "大语言模型（Large Language Model, LLM）是一种基于深度学习技术的人工智能模型，旨在理解和生成自然语言文本。这类模型通常使用海量的文本数据进行训练，学习语言的结构、语法和语义，以便能够生成连贯、符合上下文的文本。\n",
      "\n",
      "大语言模型的特点包括：\n",
      "\n",
      "1. **规模庞大**：通常包含亿万或甚至数百亿个参数，这使得模型能够捕捉复杂的语言模式。\n",
      "\n",
      "2. **预训练与微调**：模型首先在大规模的文本数据集上进行无监督的预训练，然后可以根据具体任务（如文本分类、问答生成等）进行微调。\n",
      "\n",
      "3. **多样化应用**：可用于文本生成、翻译、问答、对话系统、内容推荐等多种自然语言处理任务。\n",
      "\n",
      "4. **上下文理解能力**：能够理解上下文信息，生成相关的和一致的回应，使得与人类的互动更加自然。\n",
      "\n",
      "大语言模型的代表有OpenAI的GPT系列、Google的BERT和T5以及Meta的LLaMA等。尽管这些模型表现出色，但也存在一些挑战，如易产生偏见、缺乏常识推理能力和生成不准确或不合适的内容等。\n"
     ]
    }
   ],
   "execution_count": 2
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "# 2、JsonOutputParser : Json输出解析器\n",
    "\n",
    "方式1："
   ],
   "id": "bb13904c4cdedd9f"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-08-27T06:50:02.911205Z",
     "start_time": "2025-08-27T06:50:01.730387Z"
    }
   },
   "cell_type": "code",
   "source": [
    "from langchain_core.output_parsers import JsonOutputParser\n",
    "from langchain_core.prompts import ChatPromptTemplate\n",
    "\n",
    "chat_model = ChatOpenAI(model=\"gpt-4o-mini\")\n",
    "\n",
    "chat_prompt_template = ChatPromptTemplate.from_messages([\n",
    "    (\"system\", \"你是一个靠谱的{role}\"),\n",
    "    (\"human\", \"{question}\")\n",
    "])\n",
    "\n",
    "# 正确的：\n",
    "prompt = chat_prompt_template.invoke(\n",
    "    input={\"role\": \"人工智能专家\", \"question\": \"人工智能用英文怎么说？问题用q表示，答案用a表示，返回一个JSON格式的数据\"})\n",
    "\n",
    "# 错误的：\n",
    "# prompt = chat_prompt_template.invoke(input={\"role\":\"人工智能专家\",\"question\":\"人工智能用英文怎么说？\"})\n",
    "\n",
    "response = chat_model.invoke(prompt)\n",
    "# print(response.content)\n",
    "\n",
    "# 获取一个JsonOutputParser的实例\n",
    "parser = JsonOutputParser()\n",
    "\n",
    "json_result = parser.invoke(response)\n",
    "print(json_result)"
   ],
   "id": "da5f12821552c91e",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "```json\n",
      "{\n",
      "  \"q\": \"人工智能用英文怎么说？\",\n",
      "  \"a\": \"Artificial Intelligence\"\n",
      "}\n",
      "```\n",
      "{'q': '人工智能用英文怎么说？', 'a': 'Artificial Intelligence'}\n"
     ]
    }
   ],
   "execution_count": 8
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "方式2：\n",
    "\n",
    "举例1："
   ],
   "id": "d918a2a1941b3f28"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-08-27T06:50:48.741663Z",
     "start_time": "2025-08-27T06:50:48.728772Z"
    }
   },
   "cell_type": "code",
   "source": [
    "parser = JsonOutputParser()\n",
    "\n",
    "print(parser.get_format_instructions())"
   ],
   "id": "238004e6d998abb0",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Return a JSON object.\n"
     ]
    }
   ],
   "execution_count": 9
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "举例2：",
   "id": "34de02e7fc5e2439"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-08-27T06:56:06.427009Z",
     "start_time": "2025-08-27T06:56:04.968953Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 引入依赖包\n",
    "from langchain_core.output_parsers import JsonOutputParser\n",
    "from langchain_core.prompts import PromptTemplate\n",
    "\n",
    "# 初始化语言模型\n",
    "chat_model = ChatOpenAI(model=\"gpt-4o-mini\")\n",
    "\n",
    "joke_query = \"告诉我一个笑话。\"\n",
    "\n",
    "# 定义Json解析器\n",
    "parser = JsonOutputParser()\n",
    "\n",
    "#以PromptTemplate为例\n",
    "prompt_template = PromptTemplate.from_template(\n",
    "    template=\"回答用户的查询\\n 满足的格式为{format_instructions}\\n 问题为{question}\\n\",\n",
    "    partial_variables={\"format_instructions\": parser.get_format_instructions()},\n",
    ")\n",
    "\n",
    "prompt = prompt_template.invoke(input={\"question\": joke_query})\n",
    "response = chat_model.invoke(prompt)\n",
    "print(response)\n",
    "\n",
    "json_result = parser.invoke(response)\n",
    "print(json_result)"
   ],
   "id": "b0fc57c7cf2a7f84",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "content='```json\\n{\\n  \"joke\": \"为什么鸡过马路？因为它想去对面！\"\\n}\\n```' additional_kwargs={'refusal': None} response_metadata={'token_usage': {'completion_tokens': 27, 'prompt_tokens': 32, 'total_tokens': 59, 'completion_tokens_details': {'accepted_prediction_tokens': 0, 'audio_tokens': 0, 'reasoning_tokens': 0, 'rejected_prediction_tokens': 0}, 'prompt_tokens_details': {'audio_tokens': 0, 'cached_tokens': 0}}, 'model_name': 'gpt-4o-mini-2024-07-18', 'system_fingerprint': 'fp_efad92c60b', 'id': 'chatcmpl-C94MgvoSBRdCxkG0J6lBy3t0QJAoc', 'service_tier': None, 'finish_reason': 'stop', 'logprobs': None} id='run--85cc489c-68f5-4e26-bcda-ec0fa27a683e-0' usage_metadata={'input_tokens': 32, 'output_tokens': 27, 'total_tokens': 59, 'input_token_details': {'audio': 0, 'cache_read': 0}, 'output_token_details': {'audio': 0, 'reasoning': 0}}\n",
      "{'joke': '为什么鸡过马路？因为它想去对面！'}\n"
     ]
    }
   ],
   "execution_count": 11
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "知识的拓展： |",
   "id": "8e7fc9a8aada7e13"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-08-27T06:59:05.704725Z",
     "start_time": "2025-08-27T06:59:04.589067Z"
    }
   },
   "cell_type": "code",
   "source": [
    "from langchain_core.output_parsers import JsonOutputParser\n",
    "from langchain_core.prompts import ChatPromptTemplate\n",
    "\n",
    "chat_model = ChatOpenAI(model=\"gpt-4o-mini\")\n",
    "\n",
    "chat_prompt_template = ChatPromptTemplate.from_messages([\n",
    "    (\"system\", \"你是一个靠谱的{role}\"),\n",
    "    (\"human\", \"{question}\")\n",
    "])\n",
    "\n",
    "# 获取一个JsonOutputParser的实例\n",
    "parser = JsonOutputParser()\n",
    "\n",
    "# 写法1：\n",
    "# prompt = chat_prompt_template.invoke(input={\"role\":\"人工智能专家\",\"question\":\"人工智能用英文怎么说？问题用q表示，答案用a表示，返回一个JSON格式的数据\"})\n",
    "#\n",
    "# response = chat_model.invoke(prompt)\n",
    "#\n",
    "# json_result = parser.invoke(response)\n",
    "# print(json_result)\n",
    "\n",
    "\n",
    "# 写法2：\n",
    "chain = chat_prompt_template | chat_model | parser\n",
    "json_result1 = chain.invoke(\n",
    "    input={\"role\": \"人工智能专家\", \"question\": \"人工智能用英文怎么说？问题用q表示，答案用a表示，返回一个JSON格式的数据\"})\n",
    "print(json_result1)"
   ],
   "id": "236dab3e691ed536",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'q': '人工智能用英文怎么说？', 'a': 'Artificial Intelligence'}\n"
     ]
    }
   ],
   "execution_count": 12
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "针对于举例2",
   "id": "c9cb1968a6c46727"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-08-27T07:00:17.233073Z",
     "start_time": "2025-08-27T07:00:15.890887Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 引入依赖包\n",
    "from langchain_core.output_parsers import JsonOutputParser\n",
    "from langchain_core.prompts import PromptTemplate\n",
    "\n",
    "# 初始化语言模型\n",
    "chat_model = ChatOpenAI(model=\"gpt-4o-mini\")\n",
    "\n",
    "joke_query = \"告诉我一个笑话。\"\n",
    "\n",
    "# 定义Json解析器\n",
    "parser = JsonOutputParser()\n",
    "\n",
    "#以PromptTemplate为例\n",
    "prompt_template = PromptTemplate.from_template(\n",
    "    template=\"回答用户的查询\\n 满足的格式为{format_instructions}\\n 问题为{question}\\n\",\n",
    "    partial_variables={\"format_instructions\": parser.get_format_instructions()},\n",
    ")\n",
    "# 写法1：\n",
    "# prompt = prompt_template.invoke(input={\"question\":joke_query})\n",
    "# response = chat_model.invoke(prompt)\n",
    "# json_result = parser.invoke(response)\n",
    "\n",
    "chain = prompt_template | chat_model | parser\n",
    "json_result = chain.invoke(input={\"question\": joke_query})\n",
    "print(json_result)"
   ],
   "id": "ff8809e9ce218bb",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'joke': '为什么数学书总是感到沮丧？因为它有太多的问题！'}\n"
     ]
    }
   ],
   "execution_count": 13
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "# 3、XMLOutputParser XML输出解析器的使用\n",
    "\n",
    "举例1：自己在提示词模板中写明使用XML格式"
   ],
   "id": "cf7417ea3a8ad71d"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-08-27T07:38:46.893554Z",
     "start_time": "2025-08-27T07:38:40.746940Z"
    }
   },
   "cell_type": "code",
   "source": [
    "chat_model = ChatOpenAI(model=\"gpt-4o-mini\")\n",
    "\n",
    "actor_query = \"周星驰的简短电影记录\"\n",
    "response = chat_model.invoke(f\"请生成{actor_query}，将影片附在<movie></movie>标签中\")\n",
    "\n",
    "print(type(response))\n",
    "print(response.content)"
   ],
   "id": "513d106b58529af2",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'langchain_core.messages.ai.AIMessage'>\n",
      "周星驰（Stephen Chow）是一位著名的中国演员、导演和编剧，以其独特的喜剧风格和幽默才华而闻名。以下是他的几部经典电影记录：\n",
      "\n",
      "<movie>\n",
      "  <title>大话西游之月光宝盒</title>\n",
      "  <year>1995</year>\n",
      "  <description>这是一部融合了喜剧、爱情和奇幻元素的经典电影，讲述了至尊宝和紫霞仙子的爱情故事，打破了传统的西游记情节，成为华语电影的经典之作。</description>\n",
      "</movie>\n",
      "\n",
      "<movie>\n",
      "  <title>功夫</title>\n",
      "  <year>2004</year>\n",
      "  <description>这部电影是一部结合了功夫与喜剧的影片，讲述了一名小混混在意外中走上武道之路，最终成长为一名英雄的故事。该片因其独特的视听效果和幽默风格受到广泛好评。</description>\n",
      "</movie>\n",
      "\n",
      "<movie>\n",
      "  <title>食神</title>\n",
      "  <year>1996</year>\n",
      "  <description>影片讲述了一位失去厨艺的明星厨师在艰难的环境中重拾信心与技艺，并最终成为食神的励志故事，融合了美食和搞笑元素。</description>\n",
      "</movie>\n",
      "\n",
      "<movie>\n",
      "  <title>少林足球</title>\n",
      "  <year>2001</year>\n",
      "  <description>这是一部将足球与少林功夫结合的喜剧电影，讲述了一群绝望的少林寺弟子通过足球重拾信心的故事，展现了团队的力量和幽默。</description>\n",
      "</movie>\n",
      "\n",
      "<movie>\n",
      "  <title>喜剧之王</title>\n",
      "  <year>1999</year>\n",
      "  <description>本片是一部关于追求梦想的喜剧，讲述了一个在电影界挣扎奋斗的年轻人，最终找到自我价值和爱情的感人故事。</description>\n",
      "</movie>\n",
      "</movie>\n"
     ]
    }
   ],
   "execution_count": 15
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "举例2：",
   "id": "bcd4f35cc46b444f"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-08-27T07:39:56.564044Z",
     "start_time": "2025-08-27T07:39:56.533210Z"
    }
   },
   "cell_type": "code",
   "source": [
    "from langchain_core.output_parsers.xml import XMLOutputParser\n",
    "\n",
    "parser = XMLOutputParser()\n",
    "print(parser.get_format_instructions())"
   ],
   "id": "672499192541e35b",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "The output should be formatted as a XML file.\n",
      "1. Output should conform to the tags below.\n",
      "2. If tags are not given, make them on your own.\n",
      "3. Remember to always open and close all the tags.\n",
      "\n",
      "As an example, for the tags [\"foo\", \"bar\", \"baz\"]:\n",
      "1. String \"<foo>\n",
      "   <bar>\n",
      "      <baz></baz>\n",
      "   </bar>\n",
      "</foo>\" is a well-formatted instance of the schema.\n",
      "2. String \"<foo>\n",
      "   <bar>\n",
      "   </foo>\" is a badly-formatted instance.\n",
      "3. String \"<foo>\n",
      "   <tag>\n",
      "   </tag>\n",
      "</foo>\" is a badly-formatted instance.\n",
      "\n",
      "Here are the output tags:\n",
      "```\n",
      "None\n",
      "```\n"
     ]
    }
   ],
   "execution_count": 17
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "使用parser.get_format_instructions()结构实现：",
   "id": "2b92827e3cae9c16"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-08-27T07:44:26.841024Z",
     "start_time": "2025-08-27T07:44:12.789301Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 1.导入相关包\n",
    "from langchain_core.output_parsers import XMLOutputParser\n",
    "from langchain_core.prompts import PromptTemplate\n",
    "from langchain_openai import ChatOpenAI\n",
    "\n",
    "# 2. 初始化语言模型\n",
    "chat_model = ChatOpenAI(model=\"gpt-4o-mini\")\n",
    "\n",
    "# 3.测试模型的xml解析效果\n",
    "actor_query = \"生成汤姆·汉克斯的简短电影记录,使用中文回复\"\n",
    "\n",
    "# 4.定义XMLOutputParser对象\n",
    "parser = XMLOutputParser()\n",
    "\n",
    "# 5. 生成提示词模板\n",
    "prompt_template1 = PromptTemplate.from_template(\n",
    "    template=\"用户的问题：{query}\\n使用的格式：{format_instructions}\"\n",
    ")\n",
    "\n",
    "prompt_template2 = prompt_template1.partial(format_instructions=parser.get_format_instructions())\n",
    "\n",
    "\n",
    "response = chat_model.invoke(prompt_template2.invoke(input={\"query\": actor_query}))\n",
    "print(response.content)\n"
   ],
   "id": "4fbd1f190bc26e9e",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "```xml\n",
      "<电影记录>\n",
      "    <演员>\n",
      "        <名字>汤姆·汉克斯</名字>\n",
      "        <出生年份>1956</出生年份>\n",
      "        <代表作品>\n",
      "            <作品>《阿甘正传》</作品>\n",
      "            <作品>《拯救大兵瑞恩》</作品>\n",
      "            <作品>《失而复得》</作品>\n",
      "            <作品>《外星人E.T.》</作品>\n",
      "            <作品>《费城故事》</作品>\n",
      "        </代表作品>\n",
      "        <获奖经历>\n",
      "            <奖项>奥斯卡金像奖</奖项>\n",
      "            <奖项>金球奖</奖项>\n",
      "            <奖项>BAFTA奖</奖项>\n",
      "        </获奖经历>\n",
      "    </演员>\n",
      "</电影记录>\n",
      "```\n"
     ]
    }
   ],
   "execution_count": 19
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-08-27T07:45:19.297833Z",
     "start_time": "2025-08-27T07:45:19.284658Z"
    }
   },
   "cell_type": "code",
   "source": [
    "xml_result = parser.invoke(response)\n",
    "print(xml_result)"
   ],
   "id": "f7fb2cd0a5d2a722",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'电影记录': [{'演员': [{'名字': '汤姆·汉克斯'}, {'出生年份': '1956'}, {'代表作品': [{'作品': '《阿甘正传》'}, {'作品': '《拯救大兵瑞恩》'}, {'作品': '《失而复得》'}, {'作品': '《外星人E.T.》'}, {'作品': '《费城故事》'}]}, {'获奖经历': [{'奖项': '奥斯卡金像奖'}, {'奖项': '金球奖'}, {'奖项': 'BAFTA奖'}]}]}]}\n"
     ]
    }
   ],
   "execution_count": 20
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "# 4、列表解析器 CommaSeparatedListOutputParser\n",
    "\n",
    "举例1："
   ],
   "id": "51c692f7914c7cb4"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-08-27T07:53:24.197947Z",
     "start_time": "2025-08-27T07:53:24.182052Z"
    }
   },
   "cell_type": "code",
   "source": [
    "from langchain_core.output_parsers import CommaSeparatedListOutputParser\n",
    "\n",
    "output_parser = CommaSeparatedListOutputParser()\n",
    "\n",
    "# 返回一些指令或模板，这些指令告诉系统如何解析或格式化输出数据\n",
    "format_instructions = output_parser.get_format_instructions()\n",
    "print(format_instructions)\n",
    "\n",
    "messages = \"大象,猩猩,狮子\"\n",
    "result = output_parser.parse(messages)\n",
    "print(result)\n",
    "print(type(result))"
   ],
   "id": "1eb0b6a0d977a3f5",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Your response should be a list of comma separated values, eg: `foo, bar, baz` or `foo,bar,baz`\n",
      "['大象', '猩猩', '狮子']\n",
      "<class 'list'>\n"
     ]
    }
   ],
   "execution_count": 23
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "举例2：",
   "id": "84d2f61bf345cc6e"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-08-27T07:54:48.952910Z",
     "start_time": "2025-08-27T07:54:45.480125Z"
    }
   },
   "cell_type": "code",
   "source": [
    "from langchain_core.prompts import PromptTemplate\n",
    "from langchain_openai import ChatOpenAI\n",
    "from langchain.output_parsers import CommaSeparatedListOutputParser\n",
    "\n",
    "# 初始化语言模型\n",
    "chat_model = ChatOpenAI(model=\"gpt-4o-mini\")\n",
    "\n",
    "# 创建解析器\n",
    "output_parser = CommaSeparatedListOutputParser()\n",
    "\n",
    "# 创建LangChain提示模板\n",
    "chat_prompt = PromptTemplate.from_template(\n",
    "    \"生成5个关于{text}的列表.\\n\\n{format_instructions}\",\n",
    "    partial_variables={\n",
    "    \"format_instructions\": output_parser.get_format_instructions()\n",
    "    })\n",
    "\n",
    "# 提示模板与输出解析器传递输出\n",
    "# chat_prompt = chat_prompt.partial(format_instructions=output_parser.get_format_instructions())\n",
    "\n",
    "# 将提示和模型合并以进行调用\n",
    "chain = chat_prompt | chat_model | output_parser\n",
    "res = chain.invoke({\"text\": \"电影\"})\n",
    "print(res)\n",
    "print(type(res))"
   ],
   "id": "1bf93a1c7329247d",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['1. 动作片', '科幻片', '恐怖片', '喜剧片', '爱情片  ', '2. 经典电影', '现代电影', '外国电影', '动画电影', '纪录片  ', '3. 导演', '编剧', '主演', '配角', '制片人  ', '4. 票房收入', '影评评分', '观众评分', '参赛奖项', '影展获奖  ', '5. 电影类型', '放映时间', '电影时长', '电影评分', '观看方式  ']\n",
      "<class 'list'>\n"
     ]
    }
   ],
   "execution_count": 24
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "# 5、日期解析器 DatetimeOutputParser\n",
    "\n",
    "举例1："
   ],
   "id": "474f5d5fe259dde8"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-08-27T07:55:47.871300Z",
     "start_time": "2025-08-27T07:55:47.855302Z"
    }
   },
   "cell_type": "code",
   "source": [
    "from langchain.output_parsers import DatetimeOutputParser\n",
    "\n",
    "output_parser = DatetimeOutputParser()\n",
    "\n",
    "format_instructions = output_parser.get_format_instructions()\n",
    "print(format_instructions)"
   ],
   "id": "31be44d94c570175",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Write a datetime string that matches the following pattern: '%Y-%m-%dT%H:%M:%S.%fZ'.\n",
      "\n",
      "Examples: 1853-04-07T06:45:24.945854Z, 0835-04-16T12:35:51.978680Z, 1877-10-31T12:04:45.397316Z\n",
      "\n",
      "Return ONLY this string, no other words!\n"
     ]
    }
   ],
   "execution_count": 25
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "举例2：\n",
   "id": "22ca304ae03ef3db"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-08-27T07:57:33.023464Z",
     "start_time": "2025-08-27T07:57:31.874795Z"
    }
   },
   "cell_type": "code",
   "source": [
    "from langchain_openai import ChatOpenAI\n",
    "from langchain.prompts.chat import HumanMessagePromptTemplate\n",
    "from langchain_core.prompts import ChatPromptTemplate\n",
    "from langchain.output_parsers import DatetimeOutputParser\n",
    "\n",
    "chat_model = ChatOpenAI(model=\"gpt-4o-mini\")\n",
    "\n",
    "\n",
    "chat_prompt = ChatPromptTemplate.from_messages([\n",
    "    (\"system\",\"{format_instructions}\"),\n",
    "    (\"human\", \"{request}\")\n",
    "])\n",
    "\n",
    "output_parser = DatetimeOutputParser()\n",
    "\n",
    "# 方式1：\n",
    "# model_request = chat_prompt.format_messages(\n",
    "#     request=\"中华人民共和国是什么时候成立的\",\n",
    "#     format_instructions=output_parser.get_format_instructions()\n",
    "# )\n",
    "\n",
    "# response = chat_model.invoke(model_request)\n",
    "# result = output_parser.invoke(response)\n",
    "# print(result)\n",
    "# print(type(result))\n",
    "\n",
    "# 方式2：\n",
    "chain = chat_prompt | chat_model | output_parser\n",
    "resp = chain.invoke({\"request\":\"中华人民共和国是什么时候成立的\",\n",
    "                     \"format_instructions\":output_parser.get_format_instructions()})\n",
    "print(resp)\n",
    "print(type(resp))"
   ],
   "id": "81da7711676f94f7",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1949-10-01 00:00:00\n",
      "<class 'datetime.datetime'>\n"
     ]
    }
   ],
   "execution_count": 26
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
